import dayjs from 'dayjs';

/**
 * 根据生日获取周岁
 * @param strBirthday 生日字符串
 * @returns
 */
export const getAge = (strBirthday: string): number => {
  let age = 0;
  const birthDate = dayjs(strBirthday);
  const birthYear: number = birthDate.year();
  const birthMonth: number = birthDate.month() + 1;
  const birthDay: number = birthDate.day();
  const d = new Date();
  const nowYear = d.getFullYear();
  const nowMonth = d.getMonth() + 1;
  const nowDay = d.getDate();
  if (nowYear === birthYear) {
    age = 0; // 同年 则为0周岁
  } else {
    const ageDiff = nowYear - birthYear; // 年之差
    if (ageDiff > 0) {
      const monthDiff = nowMonth - birthMonth;
      if (monthDiff === 0) {
        const dayDiff = nowDay - birthDay; // 日之差
        if (dayDiff < 0) {
          age = ageDiff - 1;
        } else {
          age = ageDiff;
        }
      } else if (monthDiff < 0) {
        age = ageDiff - 1;
      } else {
        age = ageDiff;
      }
    }
  }
  return age; // 返回周岁年龄
};
